package com.geeklan.smart.ui.settings;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.widget.Toast;

import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.geeklan.base.base.BaseActivity;
import com.geeklan.smart.R;
import com.geeklan.smart.data.model.User;
import com.geeklan.smart.data.remote.oss.FileUploader;
import com.geeklan.smart.data.remote.oss.UploadCallback;
import com.geeklan.smart.data.repository.user.AccountRepository;
import com.geeklan.smart.databinding.ActivityUpdatePersonalDataBinding;
import com.geeklan.smart.permission.PermissionManager;
import com.geeklan.smart.ui.dialog.DateBottomSheetDialog;
import com.geeklan.smart.ui.dialog.EditTextAlertDialog;
import com.geeklan.smart.ui.dialog.ListDialog;
import com.geeklan.smart.ui.pet.AddPetActivity;
import com.geeklan.smart.ui.pet.AddPetInfoActivity;
import com.geeklan.smart.ui.viewmodel.user.UserViewModel;
import com.geeklan.smart.ui.viewmodel.user.UserViewModelFactory;
import com.geeklan.smart.utils.DateUtils;
import com.geeklan.smart.utils.DialogUtils;
import com.geeklan.smart.utils.GlideEngine;
import com.geeklan.smart.utils.ImagePathUtils;
import com.geeklan.smart.utils.SharedPreferencesUtil;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.List;

import gun0912.tedimagepicker.builder.TedImagePicker;

public class UpdatePersonalDataActivity extends BaseActivity<ActivityUpdatePersonalDataBinding> {
    private UserViewModel userViewModel;
    private User user;

    @Override
    protected ActivityUpdatePersonalDataBinding initBinding() {
        return ActivityUpdatePersonalDataBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        loading();
        userViewModel = new ViewModelProvider(this, new UserViewModelFactory(new AccountRepository())).get(UserViewModel.class);
        userViewModel.getUserInfoLiveData().observe(this, response -> {
            dismiss();
            user = response;
            Glide.with(this).load(user.getHeadImgUrl()).apply(RequestOptions.circleCropTransform()).into(mBinding.ivHead);
            if (user.getSex() == 1) {
                mBinding.tvSex.setText(R.string.male);
            } else if (user.getSex() == 2) {
                mBinding.tvSex.setText(R.string.female);
            }

            mBinding.tvNickname.setText(user.getNikename());
            mBinding.tvBirthday.setText(user.getBirthday());
        });

        userViewModel.getUserInfoErrorLiveData().observe(this, s -> {
            dismiss();
            user = new User();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
        userViewModel.getUserInfoByToken();


        userViewModel.getUpdateInfoLiveData().observe(this, response -> {
            dismiss();
            SharedPreferencesUtil.putString("nikename", mBinding.tvNickname.getText().toString());
        });

        userViewModel.getErrorLiveData().observe(this, s -> {
            dismiss();
            Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    protected void initView() {
        mBinding.ivBack.setOnClickListener(v -> {
            finish();
        });
        mBinding.llHead.setOnClickListener(v -> {
            checkAndRequestPermissions();
        });
        mBinding.llNickname.setOnClickListener(v -> {
            EditTextAlertDialog editTextAlertDialog = new EditTextAlertDialog(this, getString(R.string.update_nickname));
            editTextAlertDialog.setPositiveButtonText(getString(R.string.ok));
            editTextAlertDialog.setHint(user.getNikename());
            editTextAlertDialog.setOnPositiveButtonClickListener(v1 -> {
                editTextAlertDialog.dismiss();
                String nickname = editTextAlertDialog.getContentText();
                user.setNikename(nickname);
                mBinding.tvNickname.setText(nickname);
                userViewModel.updateUserInfo(user);
            });
            editTextAlertDialog.show();
        });
        mBinding.llBirthday.setOnClickListener(v -> {
            DateBottomSheetDialog dateBottomSheetDialog = new DateBottomSheetDialog(this);
            dateBottomSheetDialog.setCurrentDate(user.getNikename());
            dateBottomSheetDialog.setCancelableOutside(true); // 点击背景关闭
            dateBottomSheetDialog.setOnDateSelectedListener((year, month, day) -> {
                String brithday = year + "-" + month + "-" + day;
                mBinding.tvBirthday.setText(brithday);
                user.setBirthday(brithday);
                dateBottomSheetDialog.dismiss();
                userViewModel.updateUserInfo(user);
            });
            dateBottomSheetDialog.show();
        });
        mBinding.llSex.setOnClickListener(v -> {
            ListDialog listDialog = new ListDialog(this);
            listDialog.setupWheelViews(setItems());
            listDialog.setDialogTitle(getString(R.string.update_sex));
            listDialog.setOnBackListener(position -> {
                if (user != null) {
                    user.setSex(position + 1);
                } else {
                    user.setSex(position + 1);
                }
                if (user.getSex() == 1) {
                    mBinding.tvSex.setText(R.string.male);
                } else if (user.getSex() == 2) {
                    mBinding.tvSex.setText(R.string.female);
                }
                userViewModel.updateUserInfo(user);
            });
            listDialog.show();
        });
    }

    private List<String> setItems() {
        List<String> items = new ArrayList<>();
        items.add(getString(R.string.male));
        items.add(getString(R.string.female));
        return items;
    }

    private void checkAndRequestPermissions() {
        if (!PermissionManager.hasPermissions(this, PermissionManager.REQUIRED_PERMISSIONS)) {
            requestPermissions(PermissionManager.REQUIRED_PERMISSIONS, PERMISSION_REQ_ID);
        } else {
            showSelectPhotoDialog();
        }
    }

    private void showSelectPhotoDialog() {
        DialogUtils.showSelectDialog(this, v -> {
            PictureSelector.create(this)
                    .openGallery(SelectMimeType.ofImage()) // 选择图片
                    .setImageEngine(GlideEngine.createGlideEngine()) // 使用 Glide 加载图片
                    .setMaxSelectNum(1)
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            // 处理返回的图片
                            for (LocalMedia media : result) {
                                loading();
                                Glide.with(UpdatePersonalDataActivity.this).load(media.getRealPath()).apply(RequestOptions.circleCropTransform()).into(mBinding.ivHead);
                                uploadHead(media.getRealPath());
                            }
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
        }, v -> {
            PictureSelector.create(this).openCamera(SelectMimeType.ofImage()) // 拍照
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            for (LocalMedia media : result) {
                                loading();
                                Glide.with(UpdatePersonalDataActivity.this).load(media.getRealPath()).apply(RequestOptions.circleCropTransform()).into(mBinding.ivHead);
                                uploadHead(media.getRealPath());
                            }
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
        });
    }

    private void uploadHead(String headUri) {
        FileUploader.uploadFile(this, headUri, new UploadCallback() {
            @Override
            public void onUploadSuccess(String fileUrl) {
                user.setHeadImgUrl(fileUrl);
                userViewModel.updateUserInfo(user);
            }

            @Override
            public void onUploadFailure() {
                dismiss();
                Toast.makeText(UpdatePersonalDataActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onApplyWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            getWindow().setStatusBarColor(Color.WHITE);
            return insets;
        });
    }

    @Override
    public void networkStatus(boolean isConnected) {

    }

    @Override
    public void networkType(int type) {

    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, UpdatePersonalDataActivity.class);
        context.startActivity(intent);
    }
}